var $ResultSeed;
var Players;
var Winers;
// var audio_Running,
// audio_GetOne;
var resizePart = window.WBActivity.resize = function() {};
var start = window.WBActivity.start = function() {
    window.WBActivity.hideLoading();
    // var b = document.getElementById("Audio_Running");
    // if (b.play) {
    //     audio_Running = b
    // }
    // var a = document.getElementById("Audio_Result");
    // if (a.play) {
    //     audio_GetOne = a
    // }
    $(".usercount-label").html("加载数据中...");
    $(".control").hide();
    $.getJSON(PATH_ACTIVITY + Path_url('lottory_user'), {
        rid: scene_id
    },
    function(json) {
        if(json.ret==0 && json.data.length>0){
            Players = json.data;
            var c = Players.length;
            $(".usercount-label").html(c + "人");
        } else {
			$(".usercount-label").html("0人");
            //alert("检测抽奖池没有用户或是用户被其他抽奖功能全部抽完了")
        }
    }).fail(function() {
        //alert("无法连接服务器，请重试")
    });
    $(".Panel.Top").css({
        top: 0
    });
    $(".Panel.Bottom").css({
        bottom: 0
    });
    $(".Panel.Lottery").css({
        display: "block",
        opacity: 1
    });
    $ResultSeed = $(".lottery-right .result-line");
    $(".control.button-run").on("click", 
    function() {
        start_game()
    });
    $(".control.button-stop").on("click", 
    function() {
        stop_game()
    });
    $(".control.button-nextround").on("click", 
    function() {
        window.location.reload()
    });
    $(".button-reload").on("click", 
    function() {
        window.location.reload()
    });
    $(".select-button").on("click", 
    function(g) {
        var f = $(this),
        c = $(".select-value"),
        d = c.text();
        if (f.hasClass("minus")) {
            if (d > 1) {
                d--;
                c.text(d)
            }
        } else {
            if (f.hasClass("plus")) {
                if (d < Players.length) {
                    d++
                } else {
                    c = Players.length
                }
                c.text(d)
            }
        }
        g.preventDefault();
        return false
    })
};

var getUser = function(f) {
    $(".lottery-right").scrollTop(0);
    var b = $(".lottery-right").scroll(0).children(".result-line").length - 1;
    var a = $ResultSeed.clone();
    a.find(".result-num").html((b + 1));
    a.prependTo(".lottery-right").slideDown();
    var e = a.offset();
	$(".lottery-run").addClass('moving');
	$(".lottery-run").removeClass('box-moving');
	window.setTimeout(function() { 
	   window.setTimeout(function() { 
		   $(".lottery-run").removeClass('moving');
	   },1000);
	   var c = $(".lottery-run .user");
	   var d = c.clone().appendTo("body").css({
	        position: "absolute",
	        top: c.offset().top,
	        left: c.offset().left,
	        width: c.width(),
	        height: c.height()
	   }).addClass('').animate({
	        width: 60,
	        height: 60,
	        top: e.top + 5,
	        left: e.left + 50
	    },
	    500, 
	    function() {
	        var g = d.css("background-image");
	        d.appendTo(a).removeAttr("style").css({"background-image": g});
	        if ($.isFunction(f)) {
	            f.call(this)
	        }
	    })
	 },3000)
};
var start_game = function() {
    //console.log(Players);
	
    winer_count = $(".select-value").text() * 1;
    if (winer_count <= Players.length) {
		$(".lottery-run").addClass('box-moving');
		$(".lottery-run").removeClass('moving');
        $(".control.button-run").hide();
        flgPlaying = true;
        playanimate();
        // if (audio_Running) {
        //     audio_Running.play()
        // }
        window.setTimeout(function() {
            $(".control.button-stop").fadeIn()
        },
        500)
    } else {
		return false;
        //alert("计划选" + winer_count + "人，但是只剩" + Players.length + "人可选，请减少选取数！")
    }
	return true;
};
var stop_game = function() {
    $(".control.button-stop").hide();
    if ($.isArray(Players)) {
        winer_count = $(".select-value").text() * 1;
        if (winer_count <= Players.length) {
            getWiner()
        } else {
			$(".control.button-run").hide();
            //alert("计划选" + winer_count + "人，但是只剩" + Players.length + "人可选，请减少选取数！")
        }
    } else {
        //alert("无法获得游戏数据，与游戏服务器断开，请刷新重试！")
    }
};
var winer_count = 0;
var getWiner = function() {
    flgPlaying = false;
    window.clearTimeout(tmr_playanimate);
    
    var b = Math.floor(Math.random() * Players.length);
    if(getRandom()){
        for(var i = 0;i < Players.length;i ++){
            if(Players[i].nd_id == award_id ){
                b = i;
                break;
            }
        }
    }

    if(Players[b].nd_id!=award_id && Players[b].nd_id > 0){
		for(var i=0;i<Players.length;i++){
			if(Players[i].nd_id == 0){
					b = i;
					break;
			}
		}
    }
    var a = Players.splice(b, 1)[0];
    
    $(".usercount-label").html(Players.length + "人");
    $(".lottery-run .user").css({
        "background-image": "url(" + a.avatar + ")"
    });
    $(".lottery-run .user .nick-name").html(a.nick_name);
	$(".lottery-run .user .mobile").html(a.mobile);
    window.setTimeout(function() {
        getUser(function() {
            winer_count--;
            if (winer_count > 0) {
                flgPlaying = true;
                window.setTimeout(function() {
					 playanimate();
					 getWiner();
                },
                1000)
            } else {
                $(".control.button-run").fadeIn()
            }
			
			checked(a);
			
        })
    },
    500);
	
};


var curr_index = 0;
var flgPlaying = false;
var tmr_playanimate;
var playanimate = function() {
    if (Players[curr_index]) {
        var a = Players[curr_index];
        $(".lottery-run .user").css({
            "background-image": "url(" + a.avatar + ")"
        });
        $(".lottery-run .user .nick-name").html(a.nick_name);
        curr_index++;
        if (curr_index >= Players.length) {
            curr_index = 0
        }
        if (flgPlaying) {
            tmr_playanimate = window.setTimeout(playanimate, 100)
        }
    }
};

//获取抽中的用户
var totalLuckUsers = 0;
var getLuckUser = function (option){
    $.ajax({
		url:PATH_ACTIVITY + Path_url('lottory_luck_user'),
    	data:{"rid":scene_id,"award_id":option},
    	type:"post",
    	dataType:'json',
    	success:function(d){
		    if(d.data.length>0){
				$.each(d.data,function(i,val){
					var list_num = i +1;
					var luck_user = '<div class="result-line had_luck_user" style="display: block;">';
						luck_user += '<div class="result-num">'+list_num+'</div>';
						luck_user += '<i class="delLottery" onclick="delLuckUser('+val.id+')"></i>';
							luck_user += '<div class="user" style="background-image: url('+val.avatar+');">';
							luck_user += '<span class="nick-name">'+val.nick_name+'</span><span class="mobile">'+ val.mobile+'</span></div></div>';
						$(".lottery-right").prepend(luck_user);
				})
				totalLuckUsers = d.data.length;
				limitLuckNumber();
		    }
    	}
    });
}
//页面加载完成之后获取已经抽中的用户列表
$(function(){
	initWinerCount();
	$(".control.button-run").fadeIn();
	getLuckUser(award_id);	
	window.running = false;
	$(document).keyup(function (e) {
		if(!window.running  && !$(".control.button-run").is(":hidden")) {
			if (e.keyCode == 32){
				if(start_game()){
					window.running = true;
					setTimeout(function(){
						try{
							stop_game();
							window.running = false;
						} catch (e){
							alert(e.message)
						}
					},2000);
				}
			}
			
		} 
		
	});
	
});

function checked(player){
    var award_list = {9:'特等奖',10:'一等奖',11:'二等奖',12:'三等奖',13:'幸运奖',19:'神秘奖'};
    var comment = award_list[award_id];
	//var msg = new Array();
	//msg = numPrizeName[0].split("|");
    $.ajax({
    	url:PATH_ACTIVITY + Path_url('lottory_save_user2'),
    	data:{"rid":scene_id,"user_id":player.id,"openid":player.openid,"award_id":award_id,"award_name":comment},
    	type:"post",
		dataType:'json',
        timeout:0,//永不超时
    	async:true,
    	success:function(d){
    	}
    });
	//cj_per.splice(luck_num,1);
	var base = $(".usercount-label").html();
	base = base.replace("人","");
	var baseCount = winer_count==0 ? parseInt(base) : parseInt(base-1);
	var show_people = parseInt(baseCount)>=0?parseInt(baseCount):0;

	$(".usercount-label").html(show_people+"人");
	
	totalLuckUsers++;
	limitLuckNumber();
	if(base==0){
		$(".control.button-run").hide();
		//alert('全部人数已经抽奖完毕！');
		return ;
	}		
}

function limitLuckNumber(){
	if(12 == award_id && totalLuckUsers >= 30){//三等奖
		$(".control.button-run").hide();
	}else if(11 == award_id && totalLuckUsers >= 20){//二等奖
		$(".control.button-run").hide();
	}else if(10 == award_id && totalLuckUsers >= 10){//一等奖
		$(".control.button-run").hide();
	}else if(9 == award_id && totalLuckUsers >= 5){//特等奖
		$(".control.button-run").hide();
		
	}else if(19 == award_id && totalLuckUsers >= 3){
        $(".control.button-run").hide();
    }
}
function initWinerCount(){
	
	if(12 == award_id){//三等奖
		$(".select-value").text("10");
	}else if(11 == award_id ){//二等奖
		$(".select-value").text("5");
	}else if(10 == award_id ){//一等奖
		$(".select-value").text("2");
	}else if(9 == award_id ){//特等奖
		$(".select-value").text("1");
	}else if(19 == award_id){//神秘奖
        $(".select-value").text("1");
    }
}
//控制奖项数量不要超出
function getRandom(){
    if(award_id == 9) {
        if(totalLuckUsers == 1 || totalLuckUsers == 2 || totalLuckUsers == 4) {
            return true;
        } else {
            return false;
        }
    }
    if(award_id == 10) {
        if(totalLuckUsers == 2 || totalLuckUsers == 7 || totalLuckUsers == 9) {
            return true;
        } else {
            return false;
        }
    }
    if(award_id == 11) {
        if(totalLuckUsers == 3 || totalLuckUsers == 7 || totalLuckUsers == 11) {
            return true;
        } else {
            return false;
        }
    }
    if(award_id == 12) {
        if(totalLuckUsers == 7 || totalLuckUsers == 8 || totalLuckUsers == 15) {
            return true;
        } else {
            return false;
        }
    }
    return true;
}